/*
 * Name: Joon Ho Cho
 * Date: 10/24/2008
 * Course: 15-437
 */
package scheduler.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.mybeans.dao.DAOException;

import scheduler.controller.Action;
import scheduler.databean.User;
import scheduler.model.ScheduleDao;

import scheduler.model.Model;
import scheduler.model.UserDao;
import scheduler.model.CourseDao;
import scheduler.model.SectionDao;
import scheduler.model.LectureDao;

public class Controller extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	Model model;
	
    public void init() throws ServletException {
        model = new Model(getServletConfig());

        Action.add(new CourseAction(model));
        Action.add(new ScheduleAction(model));
        Action.add(new EditAction(model));
        Action.add(new LoginAction(model));
        Action.add(new LogoutAction(model));
        Action.add(new RegisterAction(model));
        Action.add(new RemoveAction(model));
        Action.add(new CurrentScheduleAction(model));
        Action.add(new SavedSchedulesAction(model));
        Action.add(new SearchCoursesAction(model));
        Action.add(new SetPasswordAction(model));
        Action.add(new CreateNewScheduleAction(model));
        try {
        	UserDao userDao = model.getUserDao();
        	CourseDao courseDao = model.getCourseDao();
        	SectionDao sectionDao = model.getSectionDao();
        	LectureDao lectureDao = model.getLectureDao();
        	ScheduleDao scheduleDao = model.getScheduleDao();
        	//SavedScheduleDao savedScheduleDao = model.getSavedScheduleDao();
        	
        	if(courseDao.lookup(15211) == null){
        		//int major, int level, String courseName, String description, int unit
        		courseDao.create(15, 211, "Fundamental Data Structures and Algorithms", "Fundamental Data Structures and Algorithms: Desc", 12);
        		courseDao.create(15, 212, "Principles of Programming", "Principles of Programming: Desc", 12);
        		courseDao.create(18, 220, "Fundamentals of Electrical Engineering", "Fundamentals of Electrical Engineering: Desc", 12);
        		courseDao.create(15, 111, "Intermediate/Advanced Programming", "Fundamentals of Electrical Engineering: Desc", 10);
        		courseDao.create(15, 123, "Effective Programming in C and UNIX", "Fundamentals of Electrical Engineering: Desc", 9);
        		courseDao.create(15, 213, "Introduction to Computer Systems", "Fundamentals of Electrical Engineering: Desc", 12);
        		courseDao.create(18, 100, "Introduction to Electrical and Computer Engineering", "Fundamentals of Electrical Engineering: Desc", 12);
        		
        		
        		
        		//int courseId, String lectureNumber, String[] day, String[] startTime, int[] duration, String[] classroom, String ins
        		lectureDao.create(1, "Lec TR 12:00PM 01:20PM DH 2315 Sleator, Garrod");
        		lectureDao.create(2, "Lec 1 TR 03:00PM 04:20PM BH A51 Erdmann");
        		lectureDao.create(2, "Lec 2 T 04:00PM 05:20PM CMB 1032 Cervesato");
        		lectureDao.create(3, "Lec TR 10:30AM 11:50AM PH 100 Greve, Sullivan");
        		
        		lectureDao.create(4, "Lec 1 MWF 12:30PM 01:20PM DH A310 Cortina ");
        		lectureDao.create(4, "Lec 2 MWF 01:30PM 02:20PM PH A18B Kesden ");
        		lectureDao.create(4, "Lec 3 MWF 02:30PM 03:20PM PH A18B Kesden ");
        		lectureDao.create(4, "Lec 4 TR 10:30AM 11:50AM WEH 7500 Adamchik ");
        		lectureDao.create(4, "Lec 5 TR 01:30PM 02:50PM WEH 5403 Adamchik ");
        		
        		lectureDao.create(5, "Lec 1 TR 09:00AM 10:20AM PH A18A Gunawardena ");
        		lectureDao.create(5, "Lec 2 TR 10:30AM 11:50AM WEH 5419AB Hoffman  ");
        		lectureDao.create(5, "Lec 3 TR 12:00PM 01:20PM PH A18A Gunawardena ");
        		lectureDao.create(5, "Lec 4 TR 01:30PM 02:50PM WEH 5419AB Hoffman  ");
        		lectureDao.create(5, "Lec 5 TR 03:00PM 04:20PM WEH 5419AB Hoffman  ");
        		
        		lectureDao.create(6, "Lec 1 TR 06:30PM 07:50PM WEH 7500 Kesden");
        		lectureDao.create(6, "Lec 2 TR 01:30PM 02:50PM BH A51 Pueschel");
        		
        		lectureDao.create(7, "Lec TR 01:30PM 02:50PM DH 2315 Sullivan ");
        		
        		

        		//int courseId, int lectureId, String semester, int year, String info
        		sectionDao.create(15211, 1, "Spring", 2009, "A W 09:30AM 10:20AM WEH 5310 Instructor TBA");
        		sectionDao.create(15211, 1, "Spring", 2009, "B W 10:30AM 11:20AM PH A18B Instructor TBA");
        		sectionDao.create(15211, 1, "Spring", 2009, "C W 11:30AM 12:20PM WEH 5310 Instructor TBA");
        		sectionDao.create(15211, 1, "Spring", 2009, "D W 12:30PM 01:20PM WEH 5310 Instructor TBA");
        		sectionDao.create(15211, 1, "Spring", 2009, "E W 01:30PM 02:20PM WEH 5310 Kim");
        		sectionDao.create(15211, 1, "Spring", 2009, "F W 02:30PM 03:20PM WEH 5310 Kim");
        		//sectionDao.create(15211, 1, "Spring", 2009, "G W 03:30PM 04:20PM PH 125B Instructor TBA");
        		
        		sectionDao.create(15212, 2, "Spring", 2009, "A W 12:30PM 01:20PM DH 2105 Instructor TBA");
        		sectionDao.create(15212, 2, "Spring", 2009, "B W 01:30PM 02:20PM BH 255A Instructor TBA");
        		sectionDao.create(15212, 2, "Spring", 2009, "C W 02:30PM 03:20PM WEH 5312 Instructor TBA");
        		sectionDao.create(15212, 2, "Spring", 2009, "D W 03:30PM 04:20PM WEH 5312 Instructor TBA");
        		sectionDao.create(15212, 3, "Spring", 2009, "W MW 10:30AM 11:20AM CMB 2035 Cervesato");
        		
        		sectionDao.create(18220, 4, "Spring", 2009, "A M 12:30PM 01:20PM CFA 206A John / M 06:30PM 09:20PM HH 1305");
        		sectionDao.create(18220, 4, "Spring", 2009, "B M 01:30PM 02:20PM DH 1209 Instructor TBA / T 06:30PM 09:20PM HH 1305");
        		sectionDao.create(18220, 4, "Spring", 2009, "C M 02:30PM 03:20PM WEH 8427 Instructor TBA / W 06:30PM 09:20PM HH 1305");
        		sectionDao.create(18220, 4, "Spring", 2009, "D M 02:30PM 03:20PM WEH 6423 Instructor TBA / R 06:30PM 09:20PM HH 1305");
        		
        		
        		sectionDao.create(15111, 5, "Spring", 2009, "A R 12:30PM 01:20PM WEH 5419C Cortina ");
        		sectionDao.create(15111, 5, "Spring", 2009, "B R 01:30PM 02:20PM WEH 5419D Cortina ");
        		sectionDao.create(15111, 6, "Spring", 2009, "C T 08:30AM 09:20AM WEH 5419D Kesden ");
        		sectionDao.create(15111, 6, "Spring", 2009, "D T 09:30AM 10:20AM WEH 5419D Kesden ");
        		sectionDao.create(15111, 7, "Spring", 2009, "E T 10:30AM 11:20AM WEH 5419D Kesden ");
        		sectionDao.create(15111, 7, "Spring", 2009, "F T 12:30PM 01:20PM WEH 5419C Kesden ");
        		sectionDao.create(15111, 8, "Spring", 2009, "G W 09:30AM 10:20AM WEH 5419A Adamchik ");
        		sectionDao.create(15111, 8, "Spring", 2009, "H W 10:30AM 11:20AM WEH 5419B Adamchik ");
        		sectionDao.create(15111, 9, "Spring", 2009, "I W 01:30PM 02:20PM WEH 5419A Adamchik ");
        		sectionDao.create(15111, 9, "Spring", 2009, "J W 03:30PM 04:20PM WEH 5419B Adamchik ");
        		
        		sectionDao.create(15123, 10, "Spring", 2009, "A W 08:30AM 09:20AM WEH 5419B Gunawardena  ");
        		sectionDao.create(15123, 10, "Spring", 2009, "B W 01:30PM 02:20PM WEH 5419D Gunawardena ");
        		sectionDao.create(15123, 11, "Spring", 2009, "C M 03:30PM 04:20PM WEH 5419B Hoffman ");
        		sectionDao.create(15123, 11, "Spring", 2009, "D M 12:30PM 01:20PM WEH 5419C Hoffman ");
        		sectionDao.create(15123, 12, "Spring", 2009, "E W 12:30PM 01:20PM WEH 5419B Gunawardena ");
        		sectionDao.create(15123, 12, "Spring", 2009, "F W 03:30PM 04:20PM WEH 5419A Gunawardena ");
        		sectionDao.create(15123, 13, "Spring", 2009, "G M 12:30PM 01:20PM WEH 5419D Hoffman ");
        		sectionDao.create(15123, 13, "Spring", 2009, "H M 01:30PM 02:20PM WEH 5419A Hoffman ");
        		sectionDao.create(15123, 14, "Spring", 2009, "I M 02:30PM 03:20PM WEH 5419A Hoffman ");
        		sectionDao.create(15123, 14, "Spring", 2009, "J M 03:30PM 04:20PM WEH 5419A Hoffman ");
        		
        		sectionDao.create(15213, 15, "Spring", 2009, "A M 09:30AM 10:20AM WEH 5310 Instructor TBA");
        		sectionDao.create(15213, 15, "Spring", 2009, "B M 10:30AM 11:20AM WEH 6423 Instructor TBA ");
        		sectionDao.create(15213, 15, "Spring", 2009, "C M 11:30AM 12:20PM DH 1211 Instructor TBA ");
        		sectionDao.create(15213, 15, "Spring", 2009, "D M 12:30PM 01:20PM PH 125B Instructor TBA ");
        		sectionDao.create(15213, 15, "Spring", 2009, "E M 01:30PM 02:20PM WEH 5302 Instructor TBA ");
        		sectionDao.create(15213, 16, "Spring", 2009, "F M 11:30AM 12:20PM WEH 5310 Instructor TBA ");
        		sectionDao.create(15213, 16, "Spring", 2009, "G M 12:30PM 01:20PM DH 1209 Instructor TBA ");
        		sectionDao.create(15213, 16, "Spring", 2009, "H M 01:30PM 02:20PM WEH 5310 Instructor TBA");
        		sectionDao.create(15213, 16, "Spring", 2009, "I M 02:30PM 03:20PM WEH 5310 Instructor TBA ");
        		sectionDao.create(15213, 16, "Spring", 2009, "J M 03:30PM 04:20PM WEH 5310 Instructor TBA ");
        		
        		sectionDao.create(18100, 17, "Spring", 2009, "A M 11:30AM 12:20PM HH B131 Instructor TBA / T 06:30PM 09:20PM HH A101");
        		sectionDao.create(18100, 17, "Spring", 2009, "B M 12:30PM 01:20PM WEH 5310 Instructor TBA / R 06:30PM 09:20PM HH A101");
        		sectionDao.create(18100, 17, "Spring", 2009, "C M 02:30PM 03:20PM WEH 5312 Instructor TBA / TR 03:00PM 04:20PM HH A101");
        		
        		
        		
        		
        		
        		User temp = new User("Mike");
				temp.setPassword("1234");
				temp.setNumSchedule(1);
				temp.setCurrentSchedule(0);
				userDao.create(temp);
				
				User temp2 = new User("Jane");
				temp2.setPassword("1234");
				temp2.setNumSchedule(0);
				userDao.create(temp2);
				
				User temp3 = new User("Tom");
				temp3.setPassword("1234");
				temp3.setNumSchedule(0);
				userDao.create(temp3);
				
				//String userName, int ScheduleNum, int courseId, String sectionId, int year, String semester
        		scheduleDao.create("Mike", 0, 15211, "F", 2009, "Fall").getId();
        		scheduleDao.create("Mike", 0, 15212, "C", 2009, "Fall").getId();
        		scheduleDao.create("Mike", 0, 18220, "B", 2009, "Fall").getId();
        
        	}
        	
		} catch (DAOException e) {
			e.printStackTrace();
		}
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String nextPage = performTheAction(request);
        sendToNextPage(nextPage,request,response);
    }
    
    /*
     * Extracts the requested action and (depending on whether the user is logged in)
     * perform it (or make the user login).
     * @param request
     * @return the next page (the view)
     */
    private String performTheAction(HttpServletRequest request) {
        HttpSession session     = request.getSession(true);
        String      servletPath = request.getServletPath();
        User        user        = (User) session.getAttribute("user");
        String      action  = getActionName(servletPath);

		try {
			request.setAttribute("registeredUsers", model.getUserDao().getAll());
		} catch (DAOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
        // System.out.println("servletPath="+servletPath+" requestURI="+request.getRequestURI()+"  user="+user);

        if (action.equals("register.do") || action.equals("login.do") 
        		 || action.equals("search-courses.do")) 
        		 {
        	// Allow these actions without logging in
			return Action.perform(action,request);
        }
        if (user == null && action.equals("start")) {
        	System.out.println("MAIN");
        	return "index.jsp";
        }
        
        if (user == null) {
        	// If the user hasn't logged in, direct him to the login page
			return Action.perform("login.do",request);
        }
        
        
        if (action.equals("start")) {
        	// If he's logged in but back at the /start page, send him to manage his pics
			return Action.perform("current.do",request);
        }

      	// Let the logged in user run his chosen action
		return Action.perform(action,request);
    }
    
    /*
     * If nextPage is null, send back 404
     * If nextPage starts with a '/', redirect to this page.
     *    In this case, the page must be the whole servlet path including the webapp name
     * Otherwise dispatch to the page (the view)
     *    This is the common case
     * Note: If nextPage equals "image", we will dispatch to /image.  In the web.xml file, "/image"
     *    is mapped to the ImageServlet will which return the image bytes for display.
     */
    private void sendToNextPage(String nextPage, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    	// System.out.println("nextPage="+nextPage);
    	
    	if (nextPage == null) {
    		response.sendError(HttpServletResponse.SC_NOT_FOUND,request.getServletPath());
    		return;
    	}
    	
    	if (nextPage.charAt(0) == '/') {
			String host  = request.getServerName();
			String port  = ":"+String.valueOf(request.getServerPort());
			if (port.equals(":80")) port = "";
			response.sendRedirect("http://"+host+port+nextPage);
			return;
    	}
    	
   		RequestDispatcher d = request.getRequestDispatcher("/view/"+nextPage);
   		d.forward(request,response);
    }

	/*
	 * Returns the path component after the last slash removing any "extension"
	 * if present.
	 */
    private String getActionName(String path) {
    	// 
        int slash = path.lastIndexOf('/');
        return path.substring(slash+1);
    }
}
